<template>
  <div class="container">
    <div class="app-container">
      <!-- data属性是树的数据，数据肯定是树形结构 -->
      <!-- props属性是展示规则，label是显示的文字的字段名是什么； children是子集存储的元素在哪个字段里面 -->
      <el-row style="padding: 30px">
        <el-col :span="18" :offset="3">
          <el-tree default-expand-all :data="list" :props="defaultProps">
            <!-- slot-scope="{ data }"  data就是每行的数据 -->
            <el-row style="width: 100%" slot-scope="{ data }">
              <el-col :span="4">{{ data.name }}</el-col>
              <el-col :span="2" :offset="14">{{ data.managerName }}</el-col>
              <el-col :span="4">
                <el-dropdown @command="clickHandler($event, data.id)">
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add"
                      >添加子部门</el-dropdown-item
                    >
                    <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-tree>
        </el-col>
      </el-row>
    </div>
    <!-------------------->
    <add-dept @updateList="initData" ref="addDept" />
  </div>
</template>
<script>
import { delDepartmentInfoApi, getDepartmentListApi } from "@/api/department";
import { transListToTreeData } from "@/utils/index";
import addDept from "./components/add-dept.vue";
export default {
  name: "Department",
  components: { addDept },
  data() {
    return {
      list: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  created() {
    this.initData();
  },
  methods: {
    // 获取部门列表
    async initData() {
      // 发起网络请求
      let res = await getDepartmentListApi();
      // 赋值数据
      this.list = transListToTreeData(res, 0);
    },
    // 点击下拉
    clickHandler(val, rowId) {
      if (val === "add") {
        // 添加操作
        // 弹框打开
        this.$refs.addDept.isShow = true;
        // 设置ID
        this.$refs.addDept.formData.pid = rowId;
      }
      if (val === "edit") {
        // 修改操作
        // 调用回显的方法
        this.$refs.addDept.replyViewData(rowId);
      }
      if (val === "del") {
        // 删除操作
        this.delRow(rowId);
      }
    },
    // 删除事件
    async delRow(id) {
      try {
        // 1. 弹出确认框
        await this.$confirm("确认删除吗");
        // 2. 发起删除请求
        await delDepartmentInfoApi(id)
        // 3. 提示成功
        this.$message.success('删除成功')
        // 4. 获取列表
        this.initData()
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>
